//
//  SendItemHelper.m
//  Etion
//
//  Created by  user on 11-4-20.
//  Copyright 2011 GuangZhouXuanWu. All rights reserved.
//

#import "XLGSendItem+SendItemHelper.h"

#import "XLGSendQueueManagerInternal.h"

#import "XLGSendQueueIndex.h"

#import "XLGPackFileUp.h"

#import "GWService.h"

#import <CommonCrypto/CommonDigest.h>

@interface XLGSendItem (XLGSendItemHelperDelegate)<CGWServiceDelegate>

@end

@implementation XLGSendItem (SendItemHelper)

- (void)sendItemWillSendFileNumsAtIndex:(NSUInteger)index totleNum:(NSUInteger)num fileName:(NSString *)name
{
    [_sendQueueManager->_uilockqueue dispatchThreadAsync:^
    {
        for (NSUInteger i = 0; i < _arSendItemDelegate.count; i++)
        {
            if ([[_arSendItemDelegate objectAtIndex:i] respondsToSelector:@selector(sendItem:willSendFileNumsAtIndex:totleNum:fileName:)])
            {
                [[_arSendItemDelegate objectAtIndex:i] sendItem:self willSendFileNumsAtIndex:index totleNum:num fileName:name];
            }
        }
    }];
}

-(void)GWService:(CGWService *)service willSendTotalBytes:(NSUInteger)bytes
{
    [self totalWillSendBytes:bytes];
}

-(void)GWService:(CGWService *)service hadSendBytes:(NSUInteger)bytes
{
    [self hadSendedBytes:bytes];
}

- (void)totalWillSendBytes:(NSUInteger)nBytes
{
    [_sendQueueManager->_uilockqueue dispatchThreadAsync:^
    {
        switch (_sbtype)
        {
            case XLGSendBytesTypeNone:
            case XLGSendBytesTypeDataPack:
            case XLGSendBytesTypeMedia:
            {
                _nTotalwillsendbytes = nBytes;
                
                for (NSUInteger i = 0; i < _arSendItemDelegate.count; i++)
                {
                    id<XLGSendItemDelegate> item = (id<XLGSendItemDelegate>)[_arSendItemDelegate objectAtIndex:i];
                    if([item respondsToSelector:@selector(sendItem:totalWillSendBytes:)])
                        [item sendItem:self totalWillSendBytes:nBytes];
                }
                
                break;
            }
        }
    }];
}

- (void)hadSendedBytes:(NSUInteger)nBytes
{
    [_sendQueueManager->_uilockqueue dispatchThreadAsync:^
    {
        switch (_sbtype)
        {
            case XLGSendBytesTypeNone:
            case XLGSendBytesTypeDataPack:
            {
                _nHadsendedbytes = nBytes;
                
                for (NSUInteger i = 0; i < _arSendItemDelegate.count; i++)
                {
                    id<XLGSendItemDelegate> item = (id<XLGSendItemDelegate>)[_arSendItemDelegate objectAtIndex:i];
                    if([item respondsToSelector:@selector(sendItem:hadSendedBytes:)])
                        [item sendItem:self hadSendedBytes:nBytes];
                }
                break;
            }
            case XLGSendBytesTypeMedia:
            {
                _nHadsendedbytes += nBytes;
                
                for (NSUInteger i = 0; i < _arSendItemDelegate.count; i++)
                {
                    id<XLGSendItemDelegate> item = (id<XLGSendItemDelegate>)[_arSendItemDelegate objectAtIndex:i];
                    if([item respondsToSelector:@selector(sendItem:hadSendedBytes:)])
                        [item sendItem:self hadSendedBytes:_nHadsendedbytes];
                }
                break;
            }
        }
    }];
}

- (void)updateSendingFile:(NSString *)szFilename
{
    [_sendQueueManager->_uilockqueue dispatchThreadAsync:^
    {
        for (NSUInteger i = 0; i < _arSendItemDelegate.count; i++)
        {
            id<XLGSendItemDelegate> item = (id<XLGSendItemDelegate>)[_arSendItemDelegate objectAtIndex:i];
            if([item respondsToSelector:@selector(sendItem:updateSendingFile:)])
                [item sendItem:self updateSendingFile:szFilename];
        }
    }];
}

- (NSArray*)findNeedSendFile:(NSString *)szPath
{
    NSArray *arFile = nil;
    [XMSFileHelper isDirEmpty:szPath containFiles:&arFile];
    NSMutableArray *needSendfile = [[NSMutableArray new] autorelease_mm];
    //找出ws⋯⋯文件
    for (NSString *filename in arFile)
    {
        NSString *pathext = [filename pathExtension];
        if (0 == [pathext compare:@"ws" options:NSCaseInsensitiveSearch range:NSMakeRange(0, 2)])
        {
            XLGSendFileName *name = [[XLGSendFileName new] autorelease_mm];
            name.fileName = filename;
            name.fileExt = pathext;
//			if(0==[pathext compare:WSDSKVE]||0==[pathext compare:WSAFFAIRKVE])
//				[(*arNeedsendfile) insertObject:name atIndex:0];
//			else
//				[(*arNeedsendfile) addObject:name];
            if (0 == [pathext compare:WSIMAGEE] || 0 == [pathext compare:WSRADIOE])
                [needSendfile insertObject:name atIndex:0];
            else
                [needSendfile addObject:name];
        }
    }
    return needSendfile;
}

- (XLGResult*)uploadFile:(XLGPackFileInfo *)uploadfile
{
    if (uploadfile != nil && uploadfile.packFileData == nil)
    {
        // 当安装新包之后会导致旧的发送队列中的图片地址更换，因此需要查找其新地址以便发送
        if (uploadfile.fullPath.length > 0 && [XMSFileHelper isFileExist:uploadfile.fullPath] == NO)
        {
            NSRange range1 = [uploadfile.fullPath rangeOfString:@"Applications/"];
            NSRange range2 = [uploadfile.fullPath rangeOfString:@"/Documents"];
            if (range1.length > 0 && range2.length > 0)
            {
                NSString *curPath = NSHomeDirectory();
                NSString *newPath = [uploadfile.fullPath stringByReplacingCharactersInRange:NSMakeRange(range1.location+range1.length, range2.location-(range1.location+range1.length)) withString:curPath.lastPathComponent];
                
                if ([XMSFileHelper isFileExist:newPath] == YES)
                {
                    uploadfile.fullPath = newPath;
                }
            }
        }
    }

    XLGResult *result = [XLGResult result];
    
    XLGPackFileUp *packfileup = [[[XLGPackFileUp alloc]initWithDataOperationManagerDelegate:nil AttachDOM:_managerService] autorelease_mm];
    if(packfileup != nil)
    {
        packfileup.service.delegate = self;
        result = [packfileup queryFSFiles:uploadfile.fileName fileData:uploadfile.packFileData paras:nil];
        if (YES == result.outResult)
        {
            XLGPackUpFileObj *output = (XLGPackUpFileObj *)result.outObj;
            if (output.URL.length > 0)//已经上传成功
            {
                result = [XLGResult resultWithOutResult:YES outObj:output.URL outError:nil];
            }
            else
            {
                _sbtype = XLGSendBytesTypeMedia;
                NSData *data = uploadfile.packFileData;
                [self totalWillSendBytes:data.length - [packfileup caleFileUploadLength:output]];
                
                result = [packfileup uploadFSChunksPackage:output fileData:data paras:nil];
            }
            if (YES != result.outResult)
                result = [XLGResult result];
        }
        else
            result = [XLGResult result];
        [_managerService detachDataOperationManager:@[packfileup]];
    }
    return result;
}

- (XLGResult*)sendItemProc
{
    XLGResult *r = nil;
    
    NSString *path = [NSString stringWithFormat:@"%@/%@/%@", [XLGContext context].m_szUserdefaulteppath, XLGSendQueueDataFolder, _mi.extendID];
    NSMutableArray *needSendFile = [[self findNeedSendFile:path] mutableCopy];
    
    NSString *path2 = [path stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.%@", _mi.extendID, WSMULTIMEDIA]];
    [needSendFile removeObject:path2];
    
    for (XLGSendFileName *sfn in needSendFile)
    {
        if ([sfn.fileExt isEqualToString:WSMULTIMEDIA])
        {
            [needSendFile removeObject:sfn];
            break;
        }
    }
    NSUInteger fileCount = needSendFile.count;
    
    for (NSUInteger i = 0; i < fileCount && NO == _bWillenterforceground; i++)
    {
        r = [XLGResult result];
        
        _sbtype = XLGSendBytesTypeNone;
        [self sendItemWillSendFileNumsAtIndex:i totleNum:fileCount fileName:nil];
        [self totalWillSendBytes:0];
        [self hadSendedBytes:0];
        XLGSendFileName *filename = [needSendFile objectAtIndex:i];
        NSString *path1 = [path stringByAppendingPathComponent:filename.fileName];
        if ([filename.fileExt isEqualToString:WSDSKVE])
        {
            [self updateSendingFile:@"正在发送"];
            _sbtype = XLGSendBytesTypeDataPack;
            
            @autoreleasepool
            {
                r = [[self sendItemDataFormatCategoryOpeateion:_mi.extendID sendType:_mi.sendType textCache:path1 multiMediaCache:path2 messageManagerAttach:_managerService] retain_mm];
            }
            [r autorelease_mm];
            
            if(r.outResult == YES)
                [XMSFileHelper deleteFileDir:path2];
        }
        else if ([filename.fileExt isEqualToString:WSIMAGEE] || [filename.fileExt isEqualToString:WSRADIOE])
        {
            [self updateSendingFile:@"正在发送"];
            
            XLGPackFileInfo *uploadfile = [NSKeyedUnarchiver unarchiveObjectWithFile:path1];
            XLGResult *result = [self uploadFile:uploadfile];
            
            @autoreleasepool
            {
                r = [[XLGResult resultWithOutResult:result.outResult outObj:nil outError:result.outError] retain_mm];
            }
            [r autorelease_mm];
            
            NSString *fileURL = (NSString*)result.outObj;
            
            if (result.outResult == YES)
            {
                NSMutableDictionary* dic = [[NSMutableDictionary new] autorelease_mm];
                [dic setDictionary:[NSDictionary dictionaryWithContentsOfFile:path2]];
                if([filename.fileExt isEqualToString:WSIMAGEE])
                {
                    NSMutableDictionary *dicF = [dic objectForKey:WSIMAGEE];
                    if(dicF == nil)
                    {
                        dicF = [[NSMutableDictionary new]autorelease_mm];
                        [dic setObject:dicF forKey:WSIMAGEE];
                    }
                    if([dicF objectForKey:uploadfile.fileName] == nil)
                        [dicF setObject:fileURL forKey:uploadfile.fileName];
                }
                else if([filename.fileExt isEqualToString:WSRADIOE])
                {
                    NSMutableDictionary *dicF = [dic objectForKey:WSRADIOE];
                    if(dicF == nil)
                    {
                        dicF = [[NSMutableDictionary new]autorelease_mm];
                        [dic setObject:dicF forKey:WSRADIOE];
                    }
                    if([dicF objectForKey:uploadfile.fileName] == nil)
                        [dicF setObject:fileURL forKey:uploadfile.fileName];
                }
                [dic writeToFile:path2 atomically:NO];
            }
        }
        
        if (YES == r.outResult)
        {
            [XMSFileHelper deleteFileDir:path1];
        }
        else if (PROTOCOLRETOBJNIL== r.outResult)
        {
            break;
        }
        else
        {
            r = [XLGResult result];
            break;
        }
    }

    return r;
}

@end
